<template>
  <section class="form-section">
    <div class="section-title">
      <el-icon><Bell /></el-icon>
      <span>通知配置</span>
    </div>

    <el-form label-width="140px">
      <el-form-item label="发送通知">
        <el-switch v-model="sendNotification" />
      </el-form-item>

      <template v-if="sendNotification">
        <el-form-item label="通知渠道">
          <el-checkbox-group v-model="channels">
            <el-checkbox label="wecom">企业微信</el-checkbox>
            <el-checkbox label="email" disabled>
              邮件
              <el-tag type="info" size="small" style="margin-left: 8px;">待开发</el-tag>
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <template v-if="channels.includes('wecom')">
          <el-form-item label="通知地址">
            <el-select
              v-model="webhookId"
              placeholder="请选择企业微信Webhook地址"
              filterable
              clearable
              style="width: 100%"
              popper-class="batch-dialog-select-popper"
              popper-append-to-body
            >
              <el-option
                v-for="webhook in wecomWebhooks"
                :key="webhook.id"
                :label="getWebhookOptionLabel(webhook)"
                :value="webhook.id"
              >
                <div style="display: flex; flex-direction: column; gap: 4px;">
                  <div style="font-weight: 500;">{{ webhook.name || '未命名' }}</div>
                  <div
                    v-if="getWebhookOptionDetail(webhook)"
                    style="font-size: 12px; color: #999; margin-top: 0; word-break: break-all;"
                  >
                    {{ getWebhookOptionDetail(webhook) }}
                  </div>
                </div>
              </el-option>
            </el-select>
            <div class="field-tip">
              请在"通知管理"中预先配置Webhook地址，然后在此处选择
            </div>
          </el-form-item>

          <el-form-item label="@指定成员">
            <el-input
              v-model="wecomMentionedList"
              placeholder="填写成员ID（userid），多个用英文逗号分隔"
            />
            <div class="field-tip">
              示例：zhangjie,baijunguang
            </div>
          </el-form-item>

          <el-form-item label="@所有人">
            <el-switch v-model="wecomMentionedAll" />
          </el-form-item>
        </template>
      </template>
      <template v-else>
        <el-form-item label="通知渠道">
          <div class="channel-disabled-tip">开启"发送通知"后可配置通知渠道及地址</div>
        </el-form-item>
      </template>
    </el-form>
  </section>
</template>

<script setup>
import { computed, ref, watch } from 'vue'
import { Bell } from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({
      send_notification: false,
      channels: [],
      webhook_id: null,
      wecom_mentioned_list: '',
      wecom_mentioned_all: false,
      wecom_mention: null
    })
  },
  webhooks: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

const sendNotification = ref(props.modelValue.send_notification ?? false)
const channels = ref(Array.isArray(props.modelValue.channels) ? [...props.modelValue.channels] : [])
const webhookId = ref(props.modelValue.webhook_id ?? null)
const wecomMentionedList = ref(props.modelValue.wecom_mentioned_list || '')
const wecomMentionedAll = ref(props.modelValue.wecom_mentioned_all ?? false)

const wecomWebhooks = computed(() => {
  return (props.webhooks || []).filter(item => item.channel_type === 'wecom' || !item.channel_type)
})

const getWebhookOptionDetail = (webhook = {}) => {
  if (!webhook) return ''
  if (typeof webhook.description === 'string' && webhook.description.trim()) {
    return webhook.description.trim()
  }
  return webhook.webhook_url || webhook.url || ''
}

const getWebhookOptionLabel = (webhook = {}) => {
  const name = webhook?.name || '未命名'
  const detail = getWebhookOptionDetail(webhook)
  return detail ? `${name} - ${detail}` : name
}

let isUpdatingFromProps = false

watch(
  () => props.modelValue,
  (val) => {
    if (!val || isUpdatingFromProps) return
    isUpdatingFromProps = true
    try {
      sendNotification.value = val.send_notification ?? false
      channels.value = Array.isArray(val.channels) ? [...val.channels] : []
      webhookId.value = val.webhook_id ?? null
      wecomMentionedList.value = val.wecom_mentioned_list || ''
      wecomMentionedAll.value = val.wecom_mentioned_all ?? false
    } finally {
      setTimeout(() => {
        isUpdatingFromProps = false
      }, 0)
    }
  },
  { immediate: true, deep: true }
)

watch(
  [sendNotification, channels, webhookId, wecomMentionedList, wecomMentionedAll],
  () => {
    if (isUpdatingFromProps) return
    const next = {
      send_notification: sendNotification.value,
      channels: [...channels.value],
      webhook_id: webhookId.value,
      wecom_mentioned_list: wecomMentionedList.value,
      wecom_mentioned_all: wecomMentionedAll.value,
      wecom_mention: props.modelValue.wecom_mention ?? null
    }
    emit('update:modelValue', next)
    emit('change', next)
  },
  { deep: true }
)

watch(sendNotification, (enabled) => {
  if (!enabled) {
    channels.value = []
    webhookId.value = null
    wecomMentionedList.value = ''
    wecomMentionedAll.value = false
  }
})
</script>

<style scoped>
.form-section {
  margin-bottom: 24px;
  padding: 24px;
  border: 1px solid #e4e7ed;
  border-radius: 12px;
  background: linear-gradient(135deg, #ffffff 0%, #fafbfc 100%);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

.form-section:hover {
  border-color: #c0c4cc;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06);
  transform: translateY(-1px);
}

.section-title {
  display: flex;
  align-items: center;
  gap: 10px;
  font-weight: 600;
  margin-bottom: 20px;
  color: #1f2937;
  font-size: 16px;
  padding-bottom: 12px;
  border-bottom: 2px solid #f0f0f0;
  position: relative;
}

.section-title::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 60px;
  height: 2px;
  background: linear-gradient(90deg, #409eff, #67c23a);
  border-radius: 1px;
}

.section-title .el-icon {
  font-size: 18px;
  color: #409eff;
}

.form-section :deep(.el-form-item) {
  margin-bottom: 20px;
}

.form-section :deep(.el-form-item__label) {
  font-weight: 500;
  color: #374151;
  line-height: 32px;
}

.form-section :deep(.el-select) {
  width: 100%;
}

.form-section :deep(.el-select .el-input__inner) {
  border-radius: 8px;
  border: 1px solid #d1d5db;
  transition: all 0.3s ease;
}

.form-section :deep(.el-select .el-input__inner:focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

.form-section :deep(.el-switch) {
  --el-switch-on-color: #409eff;
}

.form-section :deep(.el-switch__core) {
  border-radius: 12px;
}

.form-section :deep(.el-checkbox) {
  margin-right: 16px;
  margin-bottom: 8px;
}

.form-section :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #409eff;
  border-color: #409eff;
}

.field-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
  line-height: 1.5;
}

.channel-disabled-tip {
  color: #909399;
  font-size: 13px;
  padding: 8px 0;
}
</style>
